package customerController

import (
	"WEB/models"
	"fmt"
	"github.com/astaxie/beego/orm"
	"github.com/astaxie/beego/validation"
	"log"
)

type RegisterController struct {
	BaseController
}

func (this *RegisterController) Get() {
	this.TplName = "customer/register.html"
}

func (this *RegisterController) Post() {
	u := models.User{}
	if err := this.ParseForm(&u); err != nil {
		this.TplName = "error.html"
	}
	fmt.Println(u)
	//验证表单信息
	valid := validation.Validation{}

	valid.Required(u.UserName, "UserName")
	valid.Required(u.UserPassword, "UserPassword")
	valid.Required(u.UserEmail, "Email")
	valid.Required(u.UserPhone, "UserPhone")

	valid.MaxSize(u.UserName, 63, "nameMax")
	valid.Phone(u.UserPhone, "UserPhone")
	valid.Email(u.UserEmail, "email")

	if valid.HasErrors() {
		msg := make([]string, 0)
		for _, v := range valid.Errors {
			msg = append(msg, v.Error())
		}
		this.Data["msg"] = msg
		log.Println("错误", msg)
		this.TplName = "error.html"
		return
	}
	newOrm := orm.NewOrm()
	sql := models.QueryByEqualField(u, "UserName")
	var temp models.User
	row := newOrm.Raw(sql, u.UserName).QueryRow(&temp)
	if row == nil {
		this.Data["msg"] = "账号已经被使用"
		this.TplName = "error.html"
		return
	}
	sql = models.InsertWithoutPrimaryKey(models.User{})
	fmt.Println("sql", sql)
	value := models.GetFieldValue(u, models.IsPrimaryKey)
	fmt.Println(value)
	_, row = newOrm.Raw(sql, value).Exec()
	if row != nil {
		panic(row)
	}
	this.Redirect("/customer/login", 302)
}
